#include "DList.h"

void DListInit(DListNode** pphead) { // 初始化
	*pphead = CreateDListNode(0);
	(*pphead)->prev = *pphead;  (*pphead)->next = *pphead;
}

void DListClear(DListNode* phead) {  // 清理
	assert(phead);  DListNode* cur = phead->next;
	DListNode* nextcur = cur->next;
	while (cur != phead) {
		free(cur);  cur = nextcur;
		nextcur = nextcur->next;
	}   phead->next = phead;  phead->prev = phead;
}

void DListDestory(DListNode** pphead) { // 销毁
	assert(*pphead);  DListClear(*pphead);  
	free(*pphead);  *pphead = NULL;
}

DListNode* CreateDListNode(DListDataType value) { // 创建新结点
	DListNode* NewNode = (DListNode*)malloc(sizeof(DListNode));
	NewNode->data = value;  NewNode->prev = NULL;  
	NewNode->next = NULL;   return NewNode;
}

void DListPrint(DListNode* phead) { // 打印链表
	DListNode* cur = phead->next;
	printf("head -> ");
	while (cur != phead) {
		printf("%d -> ", cur->data);
		cur = cur->next;
	}   printf("head\n");
}

void DListInsert(DListNode* pos, DListDataType value) { // 在pos前面插入结点
	assert(pos);  DListNode* newnode = CreateDListNode(value);
	DListNode* prepos = pos->prev;  prepos->next = newnode;  newnode->prev = prepos;
	newnode->next = pos;  pos->prev = newnode;
}

void DListErase(DListNode* pos) { // 删除
	assert(pos);  DListNode* prepos = pos->prev;
	DListNode* nextpos = pos->next;   free(pos);
	prepos->next = nextpos;  nextpos->prev = prepos;
}

void DListPushBack(DListNode* phead, DListDataType value) { // 尾插
	assert(phead);   DListInsert(phead, value);
}

void DListPopBack(DListNode* phead) { // 尾删
	assert(phead);   DListErase(phead->prev);
}

void DListPushFront(DListNode* phead, DListDataType value) { // 头插
	assert(phead);   DListInsert(phead->next, value);
}

void DListPopFront(DListNode* phead) { // 头删
	assert(phead);   DListErase(phead->next);
}

DListNode* DListFind(DListNode* phead, DListDataType value) { // 查找
	assert(phead);  DListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == value) { return cur; }
		cur = cur->next;
	}   return NULL;
}